package cn.lf.filter;

import cn.hutool.json.JSONObject;
import io.minio.credentials.Jwt;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Objects;

@Slf4j
public class JwtFilter extends BasicHttpAuthenticationFilter {

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {

        try {
            executeLogin(request, response);
            return true;
        } catch (Exception e) {

            String msg = e.getMessage();

            Throwable cause = e.getCause();

            if (cause!=null){
                handler(response, 500, "系统异常，请联系管理员");
            }else {
                handler(response, 401, msg);
            }

            return false;

        }

    }

    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;

        String token = httpServletRequest.getHeader("token");

        JwtToken jwtToken = new JwtToken(token);

        getSubject(request, response).login(jwtToken);

        return true;
    }

    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {

        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;

        httpServletResponse.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, httpServletRequest.getHeader(HttpHeaders.ORIGIN));
        // 允许客户端请求方法
        httpServletResponse.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,POST,OPTIONS,PUT,DELETE");

        // 允许客户端提交的Header
        String requestHeaders = httpServletRequest.getHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS);
        if (Objects.nonNull(requestHeaders) && !Objects.equals(requestHeaders, "")) {
            httpServletResponse.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, requestHeaders);
        }

        // 允许客户端携带凭证信息(是否允许发送Cookie)
        httpServletResponse.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");

        // 跨域时会首先发送一个option请求，这里我们给option请求直接返回正常状态
        if (RequestMethod.OPTIONS.name().equalsIgnoreCase(httpServletRequest.getMethod())) {
            httpServletResponse.setStatus(HttpStatus.OK.value());
            return false;
        }
        return super.preHandle(request, response);
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {

        this.sendChallenge(request,response);

        return false;
    }

    @Override
    protected boolean sendChallenge(ServletRequest request, ServletResponse response) {
        HttpServletResponse httpServletResponse = WebUtils.toHttp(response);

        httpServletResponse.setCharacterEncoding("utf-8");

        httpServletResponse.setContentType("application/json;charset=utf-8");

        httpServletResponse.setStatus(HttpStatus.OK.value());

        return false;
    }

    @Override
    protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) {

        HttpServletRequest req = (HttpServletRequest) request;

        String token = req.getHeader("token");

        return token != null;

    }

    private void handler(ServletResponse response, int code, String msg) {

        HttpServletResponse httpServletResponse = (HttpServletResponse) response;

        httpServletResponse.setStatus(HttpStatus.OK.value());

        httpServletResponse.setContentType("application/json;charset=utf-8");

        try {
            PrintWriter writer = httpServletResponse.getWriter();

            JSONObject json = new JSONObject();

            json.put("code", code);
            json.put("msg", msg);

            writer.write(json.toString());

        } catch (Exception e) {

            e.printStackTrace();

        }

    }

}
